package elastic.learn.lowrest;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicHeader;
import org.apache.http.nio.entity.NStringEntity;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.ResponseListener;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.sniff.Sniffer;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Collections;
import java.util.Map;

public class EsConnect {
    private static TransportClient client;

    public static void main(String[] args) {
        RestClient rc = generateClient();
        Sniffer sniffer = Sniffer.builder(rc).setSniffIntervalMillis(60000).build();

//        basicconnect(rc);
        putconnect(rc);
//        asyncconnect(rc);
        try {
            rc.close();
            sniffer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static TransportClient generateServerClient(){
        try {
            Settings settings = Settings.builder()
                    .put("cluster.name", "my-esLearn")  //连接的集群名
                    .put("client.transport.ignore_cluster_name", true)  //如果集群名不对，也能连接
                    .build();
            //创建client
            client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));  //主机和端口号
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成restclient
     *
     */
    public static RestClient generateClient() {
        HttpHost http = new HttpHost("127.0.0.1", 9200, "http");
        RestClientBuilder builder = RestClient.builder(http);
        RestClient restClient = builder.build();

        Header[] defaultHeaders = new Header[]{new BasicHeader("header", "value")};
        builder.setDefaultHeaders(defaultHeaders);
        builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder) {
                return requestConfigBuilder.setSocketTimeout(10000); // (4)
            }
        });

        return restClient;
    }

    /**
     * TODO: 发送基本请求
     *
     */
    public static void basicconnect(RestClient restClient) {
        try {
            Map<String, String> params = Collections.singletonMap("pretty", "true");
            Response response = restClient.performRequest("GET", "/", params);
            System.out.println(response.toString() + " basic");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * TODO: 发送基本请求
     *
     */
    public static void putconnect(RestClient restClient) {
        try {
            Map<String, String> params = Collections.emptyMap();
            String a="{\"武汉中仪物联技术股份有限公司\":[{\"经营范围\":\"物联网技术、探测技术、网络技术服务；市政工程检测技术开发；地质工程勘探技术开发；市政检测、地质勘探专业仪器的研发、生产、销售；货物进出口、技术进出口(不含国家禁止或限制进出口的货物或技术)；\"}]}";
            String jsonString = "{" +
                    "\"user\":\"kimchy\"," +
                    "\"postDate\":\"2013-01-30\"," +
                    "\"message\":\"trying out Elasticsearch\"" +
                    "}";
//            System.out.println(jsonString);
            HttpEntity entity = new NStringEntity(a, ContentType.APPLICATION_JSON);
            Response response = restClient.performRequest("PUT", "/posts/doc/2", params, entity); // （3）
            System.out.println(response.toString() + " put");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * TODO: 发送异步基本请求
     *
     */
    public static void asyncconnect(RestClient restClient) {
        ResponseListener responseListener = new ResponseListener() {

            @Override
            public void onSuccess(Response response) {
                System.out.println(response.toString());// (5)
            }
            @Override
            public void onFailure(Exception exception) {
                // (6)
            }
        };
        Map<String, String> params = Collections.singletonMap("pretty", "true");
        restClient.performRequestAsync("GET", "/posts/_search", params, responseListener); // (8)

    }
}

